import logging
import os
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.db import Link
from google.appengine.ext.webapp import template
from models import AppUser, Bookmark

class DeleteBookmarkHandler(webapp.RequestHandler):	
	def get(self):
		try:
			name = self.request.get("name")
		except:
			path = os.path.join(os.path.dirname(__file__), 'base.html')
			data = {'messages': ['No bookmark name given to delete']}
			self.response.out.write(template.render(path, data))
			return
			
		query = AppUser.all().filter('user =', users.get_current_user())
		try:
			app_user = query.fetch(1)[0]
		except:
			path = os.path.join(os.path.dirname(__file__), 'base.html')
			data = {'messages': ['You are not yourself?']}
			self.response.out.write(template.render(path, data))
			return
		
		query = Bookmark.all().filter("name =", name).filter("app_user =", app_user)
		
		try:
			bookmark = query.fetch(1)[0]
			name = bookmark.name
			url = bookmark.url
			bookmark.delete()
			logging.info("Bookmark deleted: name=%s, url=%s" % (name, url))
			self.redirect('/x')
			return
		except:
			# bookmark with that name does not exist for this user
			path = os.path.join(os.path.dirname(__file__), 'base.html')
			data = {'messages': ['No bookmark by that name was found for your user']}
			self.response.out.write(template.render(path, data))
			return
	
def main():
	app = webapp.WSGIApplication([(r'.*', DeleteBookmarkHandler)], debug=True)
	wsgiref.handlers.CGIHandler().run(app)
	
if __name__ == "__main__":
	main()